package net.hekka.canyoutalk.share.database;

import net.hekka.canyoutalk.share.constant.DatabaseType;
import java.sql.*;
import javax.sql.*;
import javax.naming.*;

/**
 * 
 * @author Administrator
 */
public class DataSourceConnector {

    public static Connection getConnection(String databaseType) throws SQLException, NamingException {

        Context ctx = null;
        DataSource ds = null;
        Connection connection = null;

        try {
            ctx = new InitialContext();

            if (databaseType.equals(DatabaseType.ORACLE)) {
                ds = (DataSource) ctx.lookup("java:comp/env/jdbc/myoracle");
            }else if (databaseType.equals(DatabaseType.MYSQL)) {
                ds = (DataSource) ctx.lookup("java:comp/env/jdbc/mySQL");
            }
            connection = ds.getConnection();
            if (connection.isClosed()) {
                connection = ds.getConnection();
            }
            return connection;

        } catch (NamingException se) {
            se.printStackTrace();
            throw se;
        } finally {
            try {
                if (ctx != null) {
                    ctx.close();
                }
            } catch (NamingException e) {
                throw new NamingException();
            }
        }
    }

    public static void cleanup(PreparedStatement ps) {
        try {
            if (ps != null) {
                ps.close();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void cleanup(Connection con) {
        try {
            if (con != null) {
                con.close();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void cleanup(Connection con, PreparedStatement ps) {
        try {
            if (ps != null) {
                ps.close();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        try {
            if (con != null) {
                con.close();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void cleanup(ResultSet rs) {
        try {
            if (rs != null) {
                rs.close();
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        }

    }
}
